// 页面逻辑代码，无法调用IDP等相关接口，但是可以使用react等ui框架或者库
import { Tree, TreeDataNode, TreeProps } from 'antd';
import * as React from 'react';
import * as ReactDOM from 'react-dom';

type NeededModelData = any[]

interface State {
    neededModelData: NeededModelData;
    selectedKey: string;
}

class MyComponent extends React.PureComponent<{}, State> {
    state: State = {
        neededModelData: [],
        selectedKey: ''
    };

    componentDidMount() {
        window.addEventListener('message', this.onmessage);
    }

    componentWillUnmount() {
        window.removeEventListener('message', this.onmessage);
    }

    private getNeededModelData = () => {
        window.parent.postMessage({ action: 'getNeededModelData' }, '*')
    }

    private onmessage = (event: MessageEvent) => {
        if (event.data.action === 'neededModelData') {
            this.setState({ neededModelData: event.data.value });
        } else if (event.data.action === 'onSelectedElementsChange') {
            this.setState({ selectedKey: event.data.value });
        }
    }

    private onSelect: TreeProps['onSelect'] = (selectedKeys) => {
        const { neededModelData } = this.state
        const [key] = selectedKeys
        this.setState({ selectedKey: key as string })
        this.highlightModel(key as string)
        console.log('selected tree: modelData: ', neededModelData.find(({ id }) => id === key))
    }
    private highlightModel = (modelId: string) => {
        console.log('highlight model: modelId: ', modelId);
        window.parent.postMessage({ action: 'highlightModel', value: modelId }, '*')
    }

    render() {
        const { neededModelData, selectedKey } = this.state;
        // console.log({ neededModelData, selectedKey });

        return (
            <>
                <div>
                    <button onClick={this.getNeededModelData}>
                        getNeededModelData
                    </button>
                    <Tree selectedKeys={[selectedKey]} onSelect={this.onSelect} treeData={neededModelData2tree(neededModelData)} />
                </div>
            </>
        );
    }
}

function neededModelData2tree(neededModelData: NeededModelData): TreeDataNode[] {
    return neededModelData.map<TreeDataNode>(item => {
        const { id, name, position, size } = item
        return {
            title: name, key: id, children: [{
                title: <pre>
                    <div>
                        名称：{name}
                    </div>
                    <div>
                        位置：{JSON.stringify(position)}
                    </div>
                    <div>
                        尺寸 {JSON.stringify(size)}
                    </div>
                </pre>,
                key: `${id}-detail`,
                selectable: false,
            }]
        }
    })
}

ReactDOM.render(<MyComponent />, document.getElementById('react-container')!)